import {messages} from "share/common";
/**
 * Created by 13576 on 2017/9/18.
 */
import React from 'react'
import {connect} from 'react-redux'
import moment from 'moment'
import menuRoute from 'routes/menuRoute'
import {Form, Input, Switch, Button, Select, DatePicker, Alert, Icon, message} from 'antd'
import budgetVersionsService from 'containers/budget-setting/budget-organization/budget-versions/budget-version.service'
import 'styles/budget-setting/budget-organization/budget-versions/new-budget-versions.scss'
import { LanguageInput } from 'components/template';

const FormItem = Form.Item;

class NewBudgetVersions extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      versionCodeError: false,
      statusError: false,
      newData: [],
      version: {},
      statusOptions:[],
      checkoutCodeData: [],
      loading: false,
      budgetVersionsDetailDetailPage: menuRoute.getRouteItem('budget-versions-detail', 'key'),    //预算版本详情的页面项
      budgetOrganization: menuRoute.getRouteItem('budget-organization-detail', 'key'),  //预算组织详情的页面项
      i18n: props.params && props.params.i18n || {},
    };
  }

  componentWillMount() {
    this.getStatusOptions();
    this.setState({
      version: this.props.params,
      i18n: this.props.i18n || {}
    })
  }

  getStatusOptions(){
    budgetVersionsService.getSystemValueList(2001).then(res => { //状态
      let statusOptions = res.data || [];
      this.setState({
        statusOptions
      })
    })
  }

  //检查处理提交数据
  handleSave = (e) => {
    this.setState({loading: true});
    e.preventDefault();
    let value = this.props.form.getFieldsValue();
    if (!this.state.statusError) {
      const toleValues = {
        ...value,
        'versionDate': value['versionDate'] ? value['versionDate'].format('YYYY-MM-DD') : '',
        'organizationId': this.props.organization.id
      };
      typeof this.state.version.id ==='undefined' ? this.saveData(toleValues) : this.updateVersion(toleValues);
    }
  };

  //保存数据
  saveData(value) {
    const { versionName, description, i18n } = this.state;
    budgetVersionsService.addVersions({ ...value, ...{ versionName, description, i18n } })
      .then((response) => {
        if (response.status === 200) {
          message.success(messages('common.create.success', { name: messages('budget-setting.key214'/*预算版本*/) }));
          this.props.close(true);
        }
      })
      .catch(e => {
        if (e.response) {
          message.error(messages('common.save.filed') + ',' + `${e.response.data.message}`);
        }
      })
      .finally(() => {
        this.setState({ loading: false });
      });
  }

  updateVersion(value) {
    const { versionName, description, i18n } = this.state;
    value.id = this.state.version.id;
    value.versionNumber = this.state.version.versionNumber;
    budgetVersionsService.updateVersions({ ...value, ...{ versionName, description, i18n } })
      .then((response) => {
        if (response.status === 200) {
          message.success(messages('common.operate.success'));
          this.props.close(true);
        }
      })
      .catch(e => {
        if (e.response) {
          message.error(messages('common.save.filed') + ',' + `${e.response.data.message}`);
        }
      })
      .finally(() => {
        this.setState({ loading: false });
      });
    ;
  }

  onCancel =()=>{
    this.props.close(true);
  };


  handleI18n = (name, value, tag) => {
    let { i18n, versionName, description } = this.state;
    if (tag === 'input') {
      i18n.versionName = value;
      versionName = name;
    } else {
      i18n.description = value;
      description = name;
    }
    this.setState({ versionName, description, i18n });
  };

  render() {

    const {getFieldDecorator} = this.props.form;
    const { version, statusOptions, versionName, description, i18n } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    return (

      <div className="new-budget-versions">
        <div className="new-budget-versions-help">
          <Alert
            message={messages('common.help')}
            description={messages('budget-setting.key215'/*一个预算组织下的版本代码不可重复，一个预算组织下只能有一个当前版本，一个预算组织下允许多个预算版本同时生效。*/)}
            type="info"
            showIcon
          />
        </div>
        <div className="new-budget-versions-from">
          <Form onSubmit={this.handleSave}>
            <FormItem {...formItemLayout}
              label={messages('budget-setting.key47'/*预算组织*/)}>
              {getFieldDecorator('organizationName',
                {
                  initialValue: this.props.organization.organizationName,
                  rules: [
                    {required: true,}
                  ],
                })(
                <Input disabled={true}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
              label={messages('budget-setting.key206'/*预算版本代码*/)}>
              {getFieldDecorator('versionCode', {
                initialValue: version.versionCode,
                rules: [{required: true, message: messages('common.please.enter')},]
              })(
                <Input />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('budget-setting.key207'/*预算版本名称*/)}>
              {getFieldDecorator('versionName', {
                initialValue: version.versionName,
                rules: [{required: true, message: messages('common.please.enter')}],
              })(
                <LanguageInput
                  name={versionName}
                  isEdit={version.id}
                  i18nName={i18n.versionName || null}
                  nameChange={(name, versionName) => this.handleI18n(name, versionName, 'input')}
                  placeholder={messages('common.please.enter')/* 请输入 */}/>
              )}

            </FormItem>
            <FormItem {...formItemLayout}
              label={messages('budget-setting.key210'/*版本状态*/)}>
              {getFieldDecorator('status', {
                initialValue: typeof version.id === 'undefined' ? "NEW" : version.status.value,
                rules: [{required: true,}],
              })(
                <Select placeholder={messages('common.please.select')}>
                  {statusOptions.map((option) => {
                    return <Option key={option.code}>{option.messageKey}</Option>
                  })}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('budget-setting.key209'/*备注*/)}>
              {getFieldDecorator('description', {
                initialValue: version.description
              })(
                <LanguageInput
                  name={description}
                  textArea
                  isEdit={version.id}
                  i18nName={i18n.description || null}
                  nameChange={(name, description) => this.handleI18n(name, description, 'textArea')}
                  placeholder={messages('common.please.enter')/* 请输入 */}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
              label={messages('budget-setting.key208'/*版本日期*/)}>
              {getFieldDecorator('versionDate',
                {
                  initialValue:typeof version.id === 'undefined'? null: moment( version.versionDate, 'YYYY-MM-DD'),
                  valuePropName: "defaultValue",
                }
              )(
                <DatePicker style={{width: 315}}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
              label={messages('budget-setting.key211'/*状态*/)}>
              {getFieldDecorator('isEnabled', {
                  valuePropName: "checked",
                  initialValue: typeof version.id === 'undefined' ? true: version.isEnabled,
                }
              )(
                <Switch checkedChildren={<Icon type="check"/>} unCheckedChildren={<Icon type="cross"/>}/>
              )}
            </FormItem>
            <div className="slide-footer">
              <Button type="primary" htmlType="submit" loading={this.state.loading}>{messages('common.save')}</Button>
              <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
            </div>
          </Form>
        </div>
      </div>

    )
  }

}


NewBudgetVersions.contextTypes = {
  router: React.PropTypes.object
}


const WrappedNewBudgetVersions = Form.create()(NewBudgetVersions);

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}

export default connect(mapStateToProps)(WrappedNewBudgetVersions);
